import 'dart:async';

import 'package:common_utils/common_utils.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:m_loading/m_loading.dart';
import 'package:flutter/src/rendering/box.dart';
import 'package:fl_chart/fl_chart.dart';
import 'package:flutter_smart_dialog/flutter_smart_dialog.dart';
import 'package:get/get.dart';
import "package:flutter_screenutil/flutter_screenutil.dart";
import 'package:yinshui_caiying/http/api_collect.dart';
import 'package:yinshui_caiying/http/api_water.dart';
import 'package:yinshui_caiying/http/http.dart';
import 'package:yinshui_caiying/model/collect_device_init_result.dart';
import 'package:yinshui_caiying/model/collect_device_switch_result.dart';
import 'package:yinshui_caiying/model/collect_device_trend_result.dart';
import 'package:yinshui_caiying/model/collect_device_unlocking_result.dart';
import 'package:yinshui_caiying/model/result_model.dart';
import 'package:yinshui_caiying/model/user_real_data_reault.dart';
import 'package:yinshui_caiying/model/waterUser_list_model.dart';
import 'package:yinshui_caiying/model/water_type_model.dart';
import 'package:yinshui_caiying/pages/water/water_user_list.dart';
import 'package:yinshui_caiying/services/common_services.dart';
import 'package:yinshui_caiying/utils/colors.dart';
import 'package:yinshui_caiying/widgets/appbar.dart';
import 'package:yinshui_caiying/widgets/action_text_button.dart';
import 'package:yinshui_caiying/widgets/border_dashed.dart';
import 'package:yinshui_caiying/widgets/datatime_range.dart';
import 'package:yinshui_caiying/widgets/form/form_with_number.dart';
import 'package:yinshui_caiying/widgets/form/form_with_singlePicker.dart';
import 'package:yinshui_caiying/widgets/form/form_with_textField.dart';
import 'package:yinshui_caiying/widgets/form/form_with_radio.dart';
import 'package:yinshui_caiying/widgets/form/form_with_textArea.dart';
import 'package:yinshui_caiying/widgets/form/form_with_adPicker.dart';
import 'package:yinshui_caiying/widgets/modal_title.dart';
import 'package:yinshui_caiying/widgets/my_dialog.dart';
import 'package:yinshui_caiying/widgets/picker/models/pickerItem_model.dart';
import 'package:yinshui_caiying/widgets/picker/models/ad_list_result_model.dart';

class WaterUserDetail extends StatelessWidget {
  int _pageIndex = 0;
  WaterUserDetailController vm = Get.put(WaterUserDetailController());
  @override
  Widget build(BuildContext context) {
    vm.context = context;
    PreferredSizeWidget appBar = BackTitleBar(
        title: '用水户及设备详情',
        action: Row(
          children: [
            // Obx(() => vm.userInfo.value.tableType == '2'
            //     ? ActionTextButton(
            //         title: '初始化',
            //         width: 70.w,
            //         height: 34.h,
            //         onPressed: () {
            //           vm._getCollectDevice();
            //         })
            //     : Container()),
            ActionTextButton(
                title: '刷新',
                width: 70.w,
                height: 34.h,
                onPressed: () {
                  vm._getUserRealData(vm.userInfo.value);
                })
          ],
        ));
    double height = appBar.preferredSize.height;
    return Scaffold(
      appBar: appBar,
      floatingActionButton: FloatingActionButton(
        child: Text(
          '操作',
          style: TextStyle(color: MyColors.main, fontSize: 46.sp),
        ),
        onPressed: () {
          // vm._getUserRealData(vm.userInfo.value);
          vm.loopGetRealData();
        },
        backgroundColor: Colors.white,
      ),
      body: SafeArea(
          child: Container(
              width: 1.sw,
              decoration: BoxDecoration(
                  gradient: LinearGradient(
                      begin: Alignment.topCenter,
                      end: Alignment.bottomCenter,
                      colors: [
                    Color.fromRGBO(6, 179, 160, 1),
                    Color.fromRGBO(11, 193, 173, 1)
                  ])),
              child: Carousel(height: height))),
    );
  }
}

class Carousel extends StatefulWidget {
  final double height;

  const Carousel({
    required this.height,
  });

  @override
  _CarouselState createState() => _CarouselState();
}

class _CarouselState extends State<Carousel> {
  WaterUserDetailController vm = Get.put(WaterUserDetailController());
  // int _pageIndex = 0;

  @override
  void initState() {
    super.initState();
  }

  @override
  void dispose() {
    // TODO: implement dispose
    if (vm._timer != null) {
      vm._timer!.cancel();
    }
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    //全屏高度
    double height = MediaQuery.of(context).size.height;
    //扣掉状态栏/工具条Appbar的高度
    // double height3 = height - kToolbarHeight / 2 - widget.height;
    double height3 = 1620.h;
    return Column(
      children: <Widget>[
        Container(
          height: height3,
          child: PageView.builder(
            pageSnapping: true,
            itemCount: 2,
            controller: vm._pageController,
            onPageChanged: (int index) {
              setState(() {
                vm._pageIndex = index;
              });
            },
            itemBuilder: (BuildContext context, int index) {
              return _buildItem(vm._pageIndex, index, height3);
            },
          ),
        ),
      ],
    );
  }

  Widget _buildItem(activeIndex, index, double height3) {
    return Center(
        child: AnimatedContainer(
            curve: Curves.easeInOut,
            duration: Duration(milliseconds: 300),
            height: activeIndex == index ? height3 : height3 - 30.h,
            margin: EdgeInsets.symmetric(vertical: 0, horizontal: 40.0.w),
            child: Stack(alignment: AlignmentDirectional.topCenter, children: <
                Widget>[
              Container(
                  width: 1.sw,
                  margin: EdgeInsets.only(top: 170.h, bottom: 170.h),
                  padding: EdgeInsets.only(top: 130.h),
                  decoration: BoxDecoration(
                      borderRadius: BorderRadius.all(Radius.circular(30.sp)),
                      color: activeIndex == index
                          ? Colors.white
                          : Color.fromRGBO(255, 255, 255, 0.7)),
                  child: activeIndex == 0 ? UserInfoCard() : EquipInfoCard()),
              Positioned(
                  top: 75.h,
                  child: Container(
                      width: 206.w,
                      height: 206.w,
                      padding: EdgeInsets.all(9.w),
                      decoration: BoxDecoration(
                          borderRadius:
                              BorderRadius.all(Radius.circular(218.w)),
                          color: Colors.white,
                          boxShadow: [
                            //卡片阴影
                            BoxShadow(
                                color: Colors.black12,
                                offset: Offset(0, 10.0),
                                blurRadius: 10.0)
                          ]),
                      child: Container(
                        width: 204.w,
                        height: 204.w,
                        decoration: BoxDecoration(
                            borderRadius:
                                BorderRadius.all(Radius.circular(216.w)),
                            color: Color.fromRGBO(216, 255, 251, 1),
                            boxShadow: [
                              //卡片阴影
                              BoxShadow(
                                  color: Colors.black12,
                                  offset: Offset(0, 10.0),
                                  blurRadius: 10.0)
                            ]),
                        child: Center(
                            child: Obx(() => Text(
                                  vm.userInfo.value.username != ''
                                      ? vm.userInfo.value.username[0]
                                      : '',
                                  style: TextStyle(
                                      fontSize: 92.sp,
                                      color: Color.fromRGBO(7, 180, 161, 1)),
                                ))),
                      ))),
              Positioned(
                  top: 460.h,
                  child: Container(
                      width: 1.sw, child: MySeparator(color: MyColors.main))),
              Positioned(
                  top: 443.h,
                  left: -18.w,
                  child: Container(
                    decoration: BoxDecoration(
                        borderRadius: BorderRadius.all(Radius.circular(35.sp)),
                        color: MyColors.main),
                    width: 35.w,
                    height: 35.w,
                  )),
              Positioned(
                  top: 443.h,
                  right: -18.w,
                  child: Container(
                    decoration: BoxDecoration(
                        borderRadius: BorderRadius.all(Radius.circular(35.sp)),
                        color: MyColors.main),
                    width: 35.w,
                    height: 35.w,
                  )),
            ])));
  }

  ///用户信息
  Widget UserInfoCard() {
    return Column(
      children: [
        Row(mainAxisAlignment: MainAxisAlignment.center, children: [
          Padding(
              padding: EdgeInsets.only(left: 84.w),
              child: Obx(() => Container(
                  child: Text(vm.userInfo.value.username,
                      overflow: TextOverflow.ellipsis,
                      style: TextStyle(
                          color: Color.fromRGBO(1, 1, 1, 1),
                          fontSize: 56.sp,
                          fontWeight: FontWeight.w500))))),
          IconButton(
              icon: Icon(
                Icons.border_color,
                color: MyColors.main,
                size: 42.sp,
              ),
              onPressed: () {
                vm.openUserInfoEditPicker();
              })
        ]),
        Container(
            width: 1.sw,
            padding: EdgeInsets.only(left: 70.w, top: 80.h, right: 81.w),
            child: Stack(
              alignment: AlignmentDirectional.topCenter,
              children: <Widget>[
                Obx(() => Column(children: [
                      userInfoText(
                          '基表号：',
                          (vm.userInfo.value.baseNum == null
                              ? '-'
                              : vm.userInfo.value.baseNum)!),
                      userInfoText('基表底数：', vm.userInfo.value.initNum),
                      vm.userInfo.value.tableType == '2'
                          ? userInfoText('采集终端ID：', vm.userInfo.value.tableNum)
                          : Container(),
                      userInfoText('用水类型：', vm.userInfo.value.priceName),
                      userInfoText(
                          '水表类型：',
                          vm.userInfo.value.tableType == '1'
                              ? '一体式水表'
                              : '分体式水表'),
                      userInfoText('身份证号：', vm.userInfo.value.identityCard),
                      userInfoText('所属表井：', vm.userInfo.value.projectName),
                      userInfoText('手机号：', vm.userInfo.value.phone),
                      userInfoText('归属地：', vm.userInfo.value.adName),
                      userInfoText('用水人口：',
                          vm.userInfo.value.familySize.toString() + '人'),
                      userInfoText('是否养殖：',
                          vm.userInfo.value.isBreeder == '1' ? '是' : '否'),
                      userInfoText(
                          '养殖说明：',
                          (vm.userInfo.value.breedNote == null
                              ? '-'
                              : vm.userInfo.value.breedNote)!),
                      userInfoText('住址：', vm.userInfo.value.address),
                    ])),
                // Obx(() => vm.userInfo.value.tableType == '2'
                //     ? Positioned(
                //         top: 67.h,
                //         right: 0.w,
                //         child: MaterialButton(
                //           minWidth: 115.w,
                //           height: 58.h,
                //           // padding: EdgeInsets.only(top: 28.sp, bottom: 16.sp),
                //           color: Color.fromRGBO(0, 191, 198, 1),
                //           child: Text('调试',
                //               style: TextStyle(
                //                   fontSize: 30.sp,
                //                   fontWeight: FontWeight.w400,
                //                   color: Colors.white)),
                //           onPressed: () {
                //             vm.openDebugging();
                //           },
                //         ))
                //     : Container()),
              ],
            )),
      ],
    );
  }

  ///设备信息
  Widget EquipInfoCard() {
    return Column(
      children: [
        Row(
            mainAxisAlignment: MainAxisAlignment.center,
            crossAxisAlignment: CrossAxisAlignment.end,
            children: [
              Padding(
                  padding:
                      EdgeInsets.only(left: 122.sp, top: 30.h, right: 56.sp),
                  child: Text('设备数据',
                      style: TextStyle(
                          color: Color.fromRGBO(1, 1, 1, 1),
                          fontSize: 56.sp,
                          fontWeight: FontWeight.w500))),
              Obx(() => Text(vm.realData.value.getStatusName(),
                  style: TextStyle(
                      color: vm.realData.value.getStatusColor(),
                      fontSize: 34.sp,
                      fontWeight: FontWeight.w400))),
            ]),
        Container(
            margin: EdgeInsets.only(top: 138.h),
            child: Obx(() => Text(
                '通讯时间：' +
                    (vm.realData.value.time == ''
                        ? '-'
                        : vm.realData.value.time),
                style: TextStyle(
                    color: Color.fromRGBO(11, 193, 173, 1),
                    fontSize: 34.sp,
                    fontWeight: FontWeight.w400)))),
        Container(
            width: 1.sw,
            padding: EdgeInsets.only(left: 69.w, top: 50.h, right: 71.w),
            child: Obx(
              () => Column(children: [
                equipInfoText(
                    type: 1,
                    title: '累计流量',
                    value: (vm.realData.value.totalFlow == null ||
                            vm.realData.value.totalFlow == ''
                        ? '-'
                        : vm.realData.value.totalFlow!),
                    unit: 'm³'),
                equipInfoText(
                    type: 2,
                    title: '信号强度',
                    value: (vm.realData.value.signal == null ||
                            vm.realData.value.signal == ''
                        ? '-'
                        : vm.realData.value.signal!)),
                equipInfoText(
                    type: 3,
                    title: '电压',
                    value: (vm.realData.value.voltage == null ||
                            vm.realData.value.voltage == ''
                        ? '-'
                        : vm.realData.value.voltage!),
                    unit: 'v',
                    sataus: Color.fromRGBO(241, 15, 15, 1)),
                equipInfoText(
                    type: 4,
                    title: '阀门状态',
                    value: vm.realData.value.getSwitchStatusName(),
                    unit: ' ',
                    sataus: vm.realData.value.getSwitchStatusColor()),
                // equipValveText(
                //     title: '阀门状态',
                //     value: vm.realData.value.switchStatus == '0' ? '开' : '关'),
              ]),
            )),
      ],
    );
  }

  Widget userInfoText(String title, String value) {
    return Container(
      width: 1.sw,
      alignment: AlignmentDirectional.topStart,
      child: Text(title + value,
          maxLines: 1,
          overflow: TextOverflow.ellipsis,
          style: TextStyle(
              height: 1.9,
              color: Color.fromRGBO(102, 102, 102, 1),
              fontSize: 34.sp,
              fontWeight: FontWeight.w400)),
    );
  }
}

class WaterUserDetailController extends GetxController {
  CommonService commonService = Get.find();
  WaterUserListPageController waterUserListPageController = Get.find();
  late BuildContext context;
  final GlobalKey<FormState> _formKey = GlobalKey<FormState>();
  final userInfo = WaterUserItemModel().obs; //用水户信息
  var username = ''.obs; //户名
  var identityCard = ''.obs; //身份证号
  var address = ''.obs; //详细地址
  final waterType = PickerItemModel().obs; //用水类型
  List<PickerItemModel> waterTypeList = []; //获用水类型列表
  var phone = ''.obs; //手机号
  final familySize = 1.obs; //用水人口
  var adId = Rx<int>(0); //归属地-id
  var adName = ''.obs; //归属地-名称
  var isBreeder = '0'.obs; //是否养殖
  var breedNote = ''.obs; //养殖说明
  var note = ''.obs; //备注
  var openMsg = 0.obs; //开启状态
  var closeMsg = 0.obs; //关闭状态
  var unlockingMsg = 0.obs; //控制状态
  var time = [].obs; //趋势图-时间
  final totalFlow = <FlSpot>[].obs; //趋势图-累计流量
  final signal = <String>[].obs; //趋势图-信号
  final voltage = <FlSpot>[].obs; //趋势图-压力
  final switchStatus = <FlSpot>[].obs; //趋势图-开关状态
  final touchedIndex = 1000.obs; //柱状图当前状态

  Timer? _timer;

  ///用户实时数据
  final realData = UserRealDataModel(
          signal: '',
          status: '',
          switchStatus: '',
          totalFlow: '',
          voltage: '',
          time: '')
      .obs;

  ///用水户id，初始化时由上个页面传入
  int id = 0;
  List<Color> gradientColors = [
    const Color(0xff23b6e6),
    const Color(0xFF03B09D),
  ];
  List breederList = [
    {'name': "否", 'value': '0'},
    {'name': "是", 'value': '1'},
  ]; //是否养殖
  @override
  void onInit() async {
    if (Get.arguments != null) {
      id = Get.arguments.id;
      _getWaterUserInfo(id);
      _pageController = PageController(
        initialPage: 0,
        viewportFraction: 0.8,
      );
    }
    super.onInit();
  }

  @override
  void onClose() {
    if (_timer != null) {
      _timer!.cancel();
    }
    super.onClose();
  }

  ///获取用户实时数据
  _getUserRealData(WaterUserItemModel item) async {
    try {
      MyDialog.showLoading(msg: '更新实时数据');
      var res = await Http().post(ApiWater.DEVICE_DATA_REAL,
          data: {'address': item.tableNum, 'ad_code': item.adCode});
      SmartDialog.dismiss();
      UserRealDataResultModel result = UserRealDataResultModel.fromJson(res);

      if (result.code == 200) {
        realData(result.content.data);
      }
    } catch (e) {}
  }

  ///获取用户实施数据静默
  _getUserRealDataQuiet(WaterUserItemModel item) async {
    try {
      // MyDialog.showLoading(msg: '更新实时数据');
      var res = await Http().post(ApiWater.DEVICE_DATA_REAL,
          data: {'address': item.tableNum, 'ad_code': item.adCode});
      // SmartDialog.dismiss();
      UserRealDataResultModel result = UserRealDataResultModel.fromJson(res);

      if (result.code == 200) {
        realData(result.content.data);
      }
    } catch (e) {}
  }

  ///用水户详情
  _getWaterUserInfo(int id) async {
    try {
      var res = await Http().post(ApiWater.WATER_USER_GET, data: {"id": id});
      WaterUserListResultModel result = WaterUserListResultModel.fromJson(res);

      if (result.code == 200) {
        userInfo(result.content.data[0]);
        _getUserRealData(userInfo.value);
      } else {}
    } catch (e) {}
  }

  ///水价类型
  _getWaterTypeList(int id) async {
    try {
      var res = await Http().post(ApiWater.WATER_PRICE_LIST, data: {
        "paginate": {"total": 0, "page": 1, "per_page": 100},
        "params": {"ad_id": id, "params": ""}
      });
      WaterTypeResultModel result = WaterTypeResultModel.fromJson(res);

      if (result.code == 200) {
        result.content.data.forEach((element) {
          waterTypeList.add(PickerItemModel(
              name: element.name, value: element.id.toString()));
        });
        waterType(waterTypeList[0]);
      } else {}
    } catch (e) {}
  }

  int _openCount = 0;
  int _closeCount = 0;
  late PageController _pageController;

  ///控制
  _getCollectControl(String value) async {
    // if (value == '0') {
    //   closeMsg.value = 1;
    // } else if (value == '1') {
    //   openMsg.value = 1;
    // }
    MyDialog.showLoading(msg: '初始中...', isUseExtraWidget: true);
    try {
      var res = await Http().post(ApiCollect.CollectDeviceSwitch, data: {
        "address": userInfo.value.tableNum,
        "open_close": value,
      });
      SmartDialog.dismiss(closeType: 1);
      CollectDeviceSwitchResultModel result =
          CollectDeviceSwitchResultModel.fromJson(res);
      if (result.code == 200) {
        SmartDialog.showToast(result.message);
        if (value == '0') {
          // closeMsg.value = 2;
          // closeMsg.value = 0;
          _openCount++;
        } else if (value == '1') {
          // openMsg.value = 2;
          // openMsg.value = 0;
          _closeCount++;
        }
        if (_openCount > 0 && _closeCount > 0) {
          _changeTestStep(3);
        }
      } else {
        SmartDialog.showToast(result.message);
        if (value == '0') {
          // closeMsg.value = 3;
          closeMsg.value = 0;
        } else if (value == '1') {
          // openMsg.value = 3;
          openMsg.value = 0;
        }
      }
    } catch (e) {
      if (value == '0') {
        closeMsg.value = 3;
      } else if (value == '1') {
        openMsg.value = 3;
      }
    }
  }

  ///控制
  _getCollectUnlocking() async {
    MyDialog.showLoading(msg: '初始中...', isUseExtraWidget: true);
    unlockingMsg.value = 1;
    try {
      var res = await Http().post(ApiCollect.CollectDeviceUnlocking, data: {
        "address": userInfo.value.tableNum,
      });
      SmartDialog.dismiss(closeType: 1);
      CollectDeviceUnlockingResultModel result =
          CollectDeviceUnlockingResultModel.fromJson(res);
      if (result.code == 200) {
        SmartDialog.showToast(result.message);
        // unlockingMsg.value = 2;
        unlockingMsg.value = 0;
      } else {
        SmartDialog.showToast(result.message);
        unlockingMsg.value = 0;
        // unlockingMsg.value = 3;
      }
    } catch (e) {
      unlockingMsg.value = 3;
    }
  }

  ///初始化
  _getCollectDevice() async {
    MyDialog.showLoading(msg: '初始中...', isUseExtraWidget: true);
    try {
      var res = await Http().post(ApiCollect.CollectDeviceInit, data: {
        "address": userInfo.value.tableNum,
        "init_num": userInfo.value.initNum,
      });
      SmartDialog.dismiss(closeType: 1);
      CollectDeviceInitResultModel result =
          CollectDeviceInitResultModel.fromJson(res);
      if (result.code == 200) {
        SmartDialog.showToast(result.message);
        _changeTestStep(2);
        // openCollectDeviceInit(context);
      } else {
        SmartDialog.showToast(result.message);
      }
    } catch (e) {
      SmartDialog.dismiss();
    }
  }

  ///变更调试进度
  _changeTestStep(int step) async {
    var step_res = await Http().post(ApiCollect.CollectEdit,
        data: {"user_id": userInfo.value.id, "step_no": step});

    ResultModel step_reslut = ResultModel.fromJson(step_res);
    if (step_reslut.code == 200) {
      userInfo.update((val) {
        val!.debugStep = step;
      });
    }
  }

  ///趋势图
  _getCollectTrend(startTime, endTime) async {
    MyDialog.showLoading(msg: '查询中...');
    try {
      var res = await Http().post(ApiCollect.CollectDeviceTrend, data: {
        "address": userInfo.value.tableNum,
        "start_time": startTime,
        "end_time": endTime,
        "ad_code": userInfo.value.adCode
      });
      SmartDialog.dismiss();
      time.clear();
      signal.clear();
      totalFlow.clear();
      voltage.clear();
      switchStatus.clear();
      CollectDeviceTrendResultModel result =
          CollectDeviceTrendResultModel.fromJson(res);
      if (result.code == 200) {
        int j = 0;
        double i = 0.0;
        result.content.data.time.forEach((element) {
          totalFlow
              .add(FlSpot(i, double.parse(result.content.data.totalFlow[j])));
          voltage.add(FlSpot(i, double.parse(result.content.data.voltage[j])));
          switchStatus.add(
              FlSpot(i, double.parse(result.content.data.switchStatus[j])));
          i++;
          j++;
        });
        time.value = result.content.data.time;
        signal.value = result.content.data.signal;
      } else {}
    } catch (e) {
      SmartDialog.dismiss();
    }
  }

  int _pageIndex = 0;

  ///调试弹窗
  openDebugging() {
    closeMsg.value = 0;
    openMsg.value = 0;
    unlockingMsg.value = 0;
    Widget DebuggingWidget = Container(
        height: 1100.h,
        width: 1.sw,
        padding: EdgeInsets.fromLTRB(77.w, 53.h, 63.w, 20.h),
        decoration: BoxDecoration(
            color: Colors.white,
            borderRadius: BorderRadius.only(
                topLeft: Radius.circular(30.w),
                topRight: Radius.circular(30.w))),
        child: Column(mainAxisAlignment: MainAxisAlignment.start, children: [
          ModalTitle(
              title: '设备调试',
              onPressed: () {
                SmartDialog.dismiss();
              }),
          Obx(() => DebugBtn(
              title: '初始化',
              value: '1',
              status: openMsg,
              onPressed: userInfo.value.debugStep >= 1
                  ? () {
                      _getCollectDevice();
                    }
                  : null)),
          Obx(() => DebugBtn(
              title: '阀门开启',
              value: '1',
              status: openMsg,
              onPressed: userInfo.value.debugStep >= 2
                  ? () {
                      _getCollectControl('1');
                    }
                  : null)),
          Obx(() => DebugBtn(
              title: '阀门关闭',
              value: '0',
              status: closeMsg,
              color: Color.fromRGBO(254, 108, 1, 1),
              onPressed: userInfo.value.debugStep >= 2
                  ? () {
                      _getCollectControl('0');
                    }
                  : null)),
          Obx(() => DebugBtn(
              title: '解除控制锁定',
              value: '2',
              status: unlockingMsg,
              onPressed: userInfo.value.debugStep >= 2
                  ? () {
                      _getCollectUnlocking();
                    }
                  : null)),
          Obx(() => DebugBtn(
              title: '核验数据',
              value: '2',
              status: unlockingMsg,
              onPressed: userInfo.value.debugStep >= 3
                  ? () async {
                      await _getUserRealData(userInfo.value);
                      _changeTestStep(4);
                      _pageController.jumpToPage(1);
                      // _pageIndex = 1;
                    }
                  : null))
        ]));
    SmartDialog.show(
        alignmentTemp: Alignment.bottomCenter,
        widget: DebuggingWidget,
        isUseExtraWidget: false);
  }

  ///初始话弹窗
  openCollectDeviceInit(context) {
    showDialog(
      context: context,
      barrierDismissible: false, //点击遮罩不关闭对话框
      builder: (context) {
        return AlertDialog(
            titlePadding: EdgeInsets.all(0),
            contentPadding: EdgeInsets.only(top: 0, bottom: 0, right: 40.sp),
            content: Container(
                height: 338.h,
                width: 784.w,
                decoration: BoxDecoration(
                    color: Colors.white,
                    borderRadius: BorderRadius.all(Radius.circular(30.sp))),
                child: Stack(
                  alignment: Alignment.center,
                  children: [
                    Text('设备初始化指令已下发',
                        style: TextStyle(
                            color: Color.fromRGBO(1, 1, 1, 1),
                            fontSize: 36.sp,
                            fontWeight: FontWeight.w400)),
                    Positioned(
                      right: 10.w,
                      top: 50.h,
                      child: ModalTitle(
                          title: '',
                          margin: 0,
                          onPressed: () {
                            Navigator.pop(context);
                          }),
                    )
                  ],
                )));
      },
    );
  }

  ///进行实施数据轮询
  loopGetRealData() {
    if (realData.value.time == '') {
      ///1.说明该水表需要现场激活,这里弹出可关闭的遮罩弹窗，提示安装人员需要按指导操作
      Get.dialog(Center(
              child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Container(
            padding: EdgeInsets.only(left: 100.w, right: 100.w),
            child: Text(
              '调试页面需要触发设备调试功能，触摸调试按钮红灯亮2秒后松开，再轻触红灯闪烁1下，间隔3次连续闪烁设备进入查找网络，稳定检测间隔闪烁1下进入4分钟链接调试状态，4分钟后需要重新触发',
              style: TextStyle(color: Colors.white),
            ),
          ),
        ],
      )))
          .onError((error, stackTrace) => _timer!.cancel())
          .then((value) => _timer!.cancel());
      _timer = Timer.periodic(Duration(milliseconds: 5000), (timer) async {
        ///定时任务
        await _getUserRealDataQuiet(userInfo.value);
        if (realData.value.time != '') {
          timer.cancel();
        }
      });
    } else {
      openDebugging();
    }
  }

  /*用水类型选择 */
  waterTypeCof(PickerItemModel value) {
    waterType(value);
  }

  /* 归属地选择 */
  adIdCof(List<AdItemModel> data) {
    adName.value = data.map((e) => e.name).toList().join('-');
    adId.value = data[data.length - 1].id;
    _getWaterTypeList(adId.value);
  }

  ///用户编辑
  openUserInfoEditPicker() {
    username.value = userInfo.value.username;
    identityCard.value = userInfo.value.identityCard;
    address.value = userInfo.value.address;
    phone.value = userInfo.value.phone;
    familySize.value = userInfo.value.familySize;
    adId.value = userInfo.value.adId;
    adName.value = userInfo.value.adName;
    isBreeder.value = userInfo.value.isBreeder;
    breedNote.value =
        (userInfo.value.breedNote != null ? userInfo.value.breedNote : '')!;
    note.value = (userInfo.value.note != null ? userInfo.value.note : '')!;
    waterType.update((val) {
      val!.name = userInfo.value.priceName;
      val.value = userInfo.value.priceId.toString();
    });
    _getWaterTypeList(userInfo.value.adId);
    showModalBottomSheet(
        context: context,
        backgroundColor: Colors.transparent,
        builder: (context) {
          return Container(
              width: 1.sw,
              padding: EdgeInsets.fromLTRB(77.w, 53.h, 63.w, 40.h),
              decoration: BoxDecoration(
                  color: Colors.white,
                  borderRadius: BorderRadius.only(
                      topLeft: Radius.circular(30.w),
                      topRight: Radius.circular(30.w))),
              child:
                  Column(mainAxisAlignment: MainAxisAlignment.start, children: [
                ModalTitle(
                    title: '用水户信息修改',
                    margin: 0,
                    onPressed: () {
                      Navigator.pop(context);
                    }),
                Expanded(
                    child: Form(
                        key: _formKey, //设置globalKey，用于后面获取FormState
                        child: Container(
                          width: 1.sw,
                          child: ListView(children: [
                            FormInput(
                              title: '姓名',
                              placeholder: '请输姓名',
                              initValue: username.value,
                              request: true,
                              onChanged: (value) {
                                username.value = value;
                              },
                            ),
                            FormInput(
                              title: '身份证号',
                              placeholder: '请输身份证号',
                              initValue: identityCard.value,
                              request: true,
                              onChanged: (value) {
                                identityCard.value = value;
                              },
                            ),
                            // FormAdPicker(
                            //     title: '归属地',
                            //     onConfirm: adIdCof,
                            //     dataList: commonService.adList,
                            //     name: adName,
                            //     value: adId),
                            FormSinglePicker(
                                title: '用水类型',
                                onConfirm: waterTypeCof,
                                dataList: waterTypeList,
                                value: waterType),
                            FormInput(
                              title: '手机号',
                              request: true,
                              initValue: phone.value,
                              placeholder: '请输手机号码',
                              keyboardType: TextInputType.phone,
                              onChanged: (value) {
                                phone.value = value;
                              },
                            ),
                            FormNumber(
                              title: '用水人口',
                              request: true,
                              controller: TextEditingController(
                                  text: familySize.value.toString()),
                              placeholder: '请输用水人口',
                              onChanged: (value) {
                                familySize.value = NumUtil.getNumByValueDouble(
                                        NumUtil.getDoubleByValueStr(value), 0)
                                    as int;
                              },
                            ),
                            FormInput(
                              title: '住址',
                              placeholder: '请输住址',
                              initValue: address.value,
                              request: true,
                              onChanged: (value) {
                                address.value = value;
                              },
                            ),
                            FormRadio(
                              title: '是否养殖',
                              dataList: breederList,
                              groupValue: isBreeder,
                            ),
                            Obx(() => isBreeder.value == '1'
                                ? FormTextArea(
                                    placeholder: '填写养殖信息',
                                    request: true,
                                    controller: TextEditingController(
                                        text: breedNote.value),
                                    onChanged: (value) {
                                      breedNote.value = value;
                                    },
                                  )
                                : Container()),
                            FormTextArea(
                              title: '备注',
                              placeholder: '填写备注信息',
                              hasBorder: false,
                              controller:
                                  TextEditingController(text: note.value),
                              onChanged: (value) {
                                note.value = value;
                              },
                            ),
                            _saveButton()
                          ]),
                        )))
              ]));
        });
  }

  ///基础验证
  _validateForm() {
    var msg = '';
    if (adId.value == null || adId.value == 0) {
      msg = '请选择行政区划';
    } else if (waterType.value.value == null) {
      msg = '请选择用水类型';
    }
    if (msg != '') {
      SmartDialog.showToast(msg, alignment: Alignment.center);
      return false;
    } else {
      return true;
    }
  }

  ///保存按钮
  _saveButton() {
    return Row(
      mainAxisAlignment: MainAxisAlignment.center,
      children: [
        Container(
          width: 724.w,
          height: 145.h,
          margin: EdgeInsets.only(top: 30.h, bottom: 120.h),
          child: ElevatedButton(
            onPressed: () async {
              if (_formKey.currentState!.validate() && _validateForm()) {
                await _saveForm();
                Get.back();
              }
            },
            child: Text('保  存'),
            style: ButtonStyle(
                foregroundColor: MaterialStateProperty.all(Colors.white),
                backgroundColor: MaterialStateProperty.all(MyColors.main),
                shape: MaterialStateProperty.all(RoundedRectangleBorder(
                    borderRadius: BorderRadius.all(Radius.circular(72.w)))),
                textStyle: MaterialStateProperty.all(TextStyle(
                  fontSize: 48.sp,
                  fontWeight: FontWeight.w500,
                ))),
          ),
        )
      ],
    );
  }

  ///保存新建用水户
  _saveForm() async {
    MyDialog.showLoading(msg: '保存用水户信息');
    try {
      var res = await Http().put(ApiWater.WATER_USER_EDIT, data: {
        "id": id,
        "family_size": familySize.value,
        "phone": phone.value,
        "note": note.value,
        "address": address.value,
        "is_breeder": isBreeder.value,
        "breed_note": breedNote.value,
        "ad_id": adId.value,
        "price_id": int.parse(waterType.value.value),
        "username": username.value,
        "identity_card": identityCard.value,
      });
      ResultModel result = ResultModel.fromJson(res);
      SmartDialog.dismiss();
      if (result.code == 200) {
        SmartDialog.showToast('修改成功!', alignment: Alignment.center);

        _getWaterUserInfo(id);
        waterUserListPageController.resetParams();
        waterUserListPageController.getWaterUserListData();
      } else {
        SmartDialog.showToast('修改失败!', alignment: Alignment.center);
      }
    } catch (e) {
      SmartDialog.dismiss();
    }
  }

  ///图表
  openChart(context, int type) {
    DateTime today = DateTime.now();
    var s_time = today.subtract(new Duration(days: 5)).toString();
    var e_time = today.toString();
    _getCollectTrend(s_time, e_time);
    showModalBottomSheet(
        context: context,
        backgroundColor: Colors.transparent,
        builder: (context) {
          return Container(
              height: 1300.h,
              width: 1.sw,
              padding: EdgeInsets.fromLTRB(77.w, 53.h, 63.w, 40.h),
              decoration: BoxDecoration(
                  color: Colors.white,
                  borderRadius: BorderRadius.only(
                      topLeft: Radius.circular(30.w),
                      topRight: Radius.circular(30.w))),
              child: Column(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    ModalTitle(
                        margin: 0,
                        title: type == 1
                            ? '累计流量运行统计'
                            : type == 2
                                ? '信号强度运行统计'
                                : type == 3
                                    ? '电压运行统计'
                                    : '开关运行统计',
                        onPressed: () {
                          Navigator.pop(context);
                        }),
                    DateTimeRanges(
                        startTime: s_time,
                        endTime: e_time,
                        onChanged: (start, end) {
                          if (start != '' && end != '') {
                            _getCollectTrend(start, end);
                          }
                        }),
                    Container(
                        width: 1.sw,
                        height: 700.h,
                        padding: EdgeInsets.only(top: 83.h, right: 40.w),
                        child: Obx(() => time.value.length != 0
                            ? type == 1
                                ? LineChart(lineChartDatas(totalFlow, 'm³'))
                                : type == 2
                                    ? BarChart(barChartDatas())
                                    : type == 3
                                        ? LineChart(
                                            lineChartDatas(voltage, 'v'))
                                        : LineChart(
                                            lineChartDatas(switchStatus, ''))
                            : Column(
                                mainAxisAlignment: MainAxisAlignment.center,
                                children: [
                                  Container(
                                      width: 300.w,
                                      child: Image(
                                          image: AssetImage(
                                              'assets/images/water_user_detail/no-data.png'),
                                          fit: BoxFit.fill)),
                                  Text('暂无数据',
                                      style: TextStyle(
                                        color: Colors.grey,
                                        fontSize: 48.sp,
                                        fontWeight: FontWeight.w500,
                                      ))
                                ],
                              )))
                  ]));
        });
  }

  ///折线图
  LineChartData lineChartDatas(RxList<FlSpot> value, String unit) {
    return LineChartData(
      lineTouchData: LineTouchData(
          touchTooltipData:
              LineTouchTooltipData(tooltipBgColor: Colors.blueGrey)),
      gridData: FlGridData(
        show: true,
        getDrawingHorizontalLine: (value) {
          return FlLine(
            color: const Color.fromRGBO(217, 217, 217, 1),
            strokeWidth: 1,
          );
        },
      ),
      titlesData: FlTitlesData(
        show: true,
        bottomTitles: SideTitles(
            showTitles: true,
            getTextStyles: (value) => const TextStyle(
                color: Color.fromRGBO(153, 153, 153, 1), fontSize: 12),
            getTitles: (value) {
              return time.value[value.toInt()] != null
                  ? time.value[value.toInt()]
                  : '';
            },
            reservedSize: 35,
            margin: 75,
            rotateAngle: -65),
        leftTitles: SideTitles(
            showTitles: true,
            getTextStyles: (value) => const TextStyle(
                color: Color.fromRGBO(153, 153, 153, 1), fontSize: 12),
            getTitles: (value) {
              return value.toInt().toString() + unit;
            },
            margin: 12),
      ),
      borderData: FlBorderData(show: true, border: Border.all(width: 0)),
      minY: 0,
      lineBarsData: [
        LineChartBarData(
          spots: value.value,
          isCurved: true,
          colors: gradientColors,
          barWidth: 2,
          isStrokeCapRound: true,
          dotData: FlDotData(
            show: false,
          ),
          belowBarData: BarAreaData(
            show: true,
            colors:
                gradientColors.map((color) => color.withOpacity(0.3)).toList(),
          ),
        ),
      ],
    );
  }

  ///柱状图
  BarChartData barChartDatas() {
    return BarChartData(
      barTouchData: BarTouchData(
        touchTooltipData: BarTouchTooltipData(
            tooltipBgColor: Colors.blueGrey,
            getTooltipItem: (group, groupIndex, rod, rodIndex) {
              return BarTooltipItem(
                (time.value[group.x.toInt()] != null
                        ? time.value[group.x.toInt()]
                        : '') +
                    '\n',
                TextStyle(
                  color: Colors.white,
                  fontWeight: FontWeight.bold,
                  fontSize: 14,
                ),
                children: <TextSpan>[
                  TextSpan(
                    text: (rod.y - 1).toString(),
                    style: TextStyle(
                      color: Colors.yellow,
                      fontSize: 12,
                      fontWeight: FontWeight.w500,
                    ),
                  ),
                ],
              );
            }),
        touchCallback: (barTouchResponse) {
          if (barTouchResponse.spot != null &&
              barTouchResponse.touchInput is! PointerUpEvent &&
              barTouchResponse.touchInput is! PointerExitEvent) {
            touchedIndex.value = barTouchResponse.spot!.touchedBarGroupIndex;
          } else {
            touchedIndex.value = 1000;
          }
        },
      ),
      gridData: FlGridData(
        show: true,
        horizontalInterval: 20,
        getDrawingHorizontalLine: (value) {
          return FlLine(
            color: const Color.fromRGBO(217, 217, 217, 1),
            strokeWidth: 1,
          );
        },
      ),
      titlesData: FlTitlesData(
        show: true,
        bottomTitles: SideTitles(
          showTitles: true,
          getTextStyles: (value) => const TextStyle(
              color: Color.fromRGBO(153, 153, 153, 1), fontSize: 12),
          margin: 70,
          rotateAngle: -65,
          getTitles: (double value) {
            return time.value[value.toInt()] != null
                ? time.value[value.toInt()]
                : '';
          },
        ),
        leftTitles: SideTitles(
            showTitles: true,
            getTextStyles: (value) => const TextStyle(
                color: Color.fromRGBO(153, 153, 153, 1), fontSize: 12),
            getTitles: (value) {
              return value.toInt().toString();
            },
            interval: 20,
            margin: 12),
      ),
      borderData: FlBorderData(
        show: false,
      ),
      minY: -100,
      maxY: 0,
      barGroups: showingGroups(),
    );
  }

  List<BarChartGroupData> showingGroups() =>
      List.generate(time.value.length, (i) {
        String value = signal.value[i];
        return makeGroupData(i, double.parse(value),
            isTouched: i == touchedIndex.value);
      });

  BarChartGroupData makeGroupData(
    int x,
    double y, {
    bool isTouched = true,
    Color barColor = MyColors.main,
    List<int> showTooltips = const [],
  }) {
    return BarChartGroupData(
      x: x,
      barRods: [
        BarChartRodData(
          y: isTouched ? y + 1 : y,
          colors: [isTouched ? Colors.yellow : barColor],
          width: 10,
          // backDrawRodData: BackgroundBarChartRodData(
          //     show: true, y: 50, colors: [const Color.fromRGBO(0, 0, 0, .2)]),
        ),
      ],
      showingTooltipIndicators: showTooltips,
    );
  }
}

/* 设备信息 */
class equipInfoText extends StatelessWidget {
  final int type;
  final String title;
  final String value;
  final String unit;
  final Color sataus;

  const equipInfoText(
      {required this.type,
      required this.title,
      this.value = '',
      this.unit = '',
      this.sataus = const Color.fromRGBO(20, 191, 20, 1)});

  @override
  Widget build(BuildContext context) {
    return Column(
      children: [
        Container(
            child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
              Row(crossAxisAlignment: CrossAxisAlignment.center, children: [
                Container(
                  margin: EdgeInsets.only(right: 21.sp),
                  decoration: BoxDecoration(
                      borderRadius: BorderRadius.all(Radius.circular(35.sp)),
                      color: sataus),
                  width: 18.w,
                  height: 18.w,
                ),
                Text(title + '：',
                    style: TextStyle(
                        color: Color.fromRGBO(102, 102, 102, 1),
                        fontSize: 34.sp,
                        fontWeight: FontWeight.w400)),
                Text(value + ' ',
                    style: TextStyle(
                        color: Colors.black,
                        fontSize: 40.sp,
                        fontWeight: FontWeight.w600)),
                Padding(
                  padding: EdgeInsets.only(top: 10.sp),
                  child: unit != ''
                      ? UnitWidget(unit: unit)
                      : SignalWidget(value: value),
                )
              ]),
              IconButton(
                  icon: Icon(
                    Icons.equalizer,
                    color: MyColors.main,
                    size: 49.sp,
                  ),
                  onPressed: () {
                    WaterUserDetailController vm =
                        Get.put(WaterUserDetailController());
                    vm.openChart(context, type);
                  })
            ])),
        MySeparator()
      ],
    );
  }
}

/* 设备开关信息 */
class equipValveText extends StatelessWidget {
  final String title;
  final String value;

  const equipValveText({required this.title, this.value = ''});

  @override
  Widget build(BuildContext context) {
    return Column(
      children: [
        Container(
            padding: EdgeInsets.only(left: 41.sp),
            child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  Text(title,
                      style: TextStyle(
                          color: Color.fromRGBO(102, 102, 102, 1),
                          fontSize: 34.sp,
                          fontWeight: FontWeight.w400)),
                  TextButton(
                      child: Text(
                        value,
                        style: TextStyle(
                            color: value == '开'
                                ? Color.fromRGBO(20, 191, 20, 1)
                                : Color.fromRGBO(241, 15, 15, 1),
                            fontSize: 40.sp,
                            fontWeight: FontWeight.w500),
                      ),
                      onPressed: () {})
                ])),
        MySeparator()
      ],
    );
  }
}

///单位展示
class UnitWidget extends StatelessWidget {
  final unit;
  UnitWidget({required this.unit});
  @override
  Widget build(BuildContext context) {
    return Text(unit,
        style: TextStyle(
            color: Color.fromRGBO(153, 153, 153, 1),
            fontSize: 28.sp,
            fontWeight: FontWeight.w400));
  }
}

//信号展示
class SignalWidget extends StatelessWidget {
  final value;
  SignalWidget({required this.value});
  @override
  Widget build(BuildContext context) {
    double nums = 0;
    if (value != '-') {
      double result = double.parse(value);
      if (result <= 33) {
        nums = 0.35;
      } else if (result > 33 && result <= 66) {
        nums = 0.7;
      } else if (result > 66) {
        nums = 1;
      }
    }
    return Container(
        width: 100.w,
        margin: EdgeInsets.only(bottom: 15.sp),
        child: Stack(
          children: <Widget>[
            Positioned(
                top: 0,
                left: 0,
                child: Icon(
                  Icons.signal_cellular_alt,
                  color: Color.fromRGBO(102, 102, 102, 1),
                  size: 49.sp,
                )),
            ClipRect(
              child: Align(
                alignment: Alignment.topLeft,
                widthFactor: nums, //宽度设为原来宽度一半 0.35 0.7 1
                child: Icon(
                  Icons.signal_cellular_alt,
                  color: Color.fromRGBO(83, 206, 15, 1),
                  size: 49.sp,
                ),
              ),
            ),
          ],
        ));
  }
}

///Color.fromRGBO(234, 3, 3, 0.6) 阀门关闭的颜色
//调试按钮
class DebugBtn extends StatelessWidget {
  final String title;
  final String value;
  final Rx<int> status;
  final Color color;
  final void Function()? onPressed;
  DebugBtn(
      {required this.title,
      required this.value,
      required this.status,
      required this.onPressed,
      this.color = const Color.fromRGBO(11, 193, 197, 1)});
  @override
  Widget build(BuildContext context) {
    WaterUserDetailController vm = Get.put(WaterUserDetailController());
    return Container(
      width: 724.w,
      height: 150.h,
      padding: EdgeInsets.only(bottom: 49.sp),
      child: ElevatedButton(
          child: Text(title),
          onPressed: onPressed,
          style: ButtonStyle(
              shape: MaterialStateProperty.all(RoundedRectangleBorder(
                  side: BorderSide.none,
                  borderRadius: BorderRadius.all(Radius.circular(72.sp)))),
              textStyle: MaterialStateProperty.all(TextStyle(
                  fontSize: 48.sp,
                  fontWeight: FontWeight.w500,
                  color: Colors.white)),
              backgroundColor: MaterialStateProperty.resolveWith((states) {
                if (this.onPressed != null) {
                  return color;
                } else {
                  return Colors.grey;
                }
              }))),
    );
  }
}
